package com.zimin.common.utils;

import com.zimin.common.constant.ThreadPoolConstant;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @Author: 嘉阳
 * @Date: 2021/1/26
 * @Describe: 线程 工具类
 */
@Slf4j
public class ThreadUtil {
//    public static final ThreadLocal threadLocal = new ThreadLocal();

    /**
     * 打印线程异常信息
     */
    public static void exception(Runnable r, Throwable t) {
        if (t == null && r instanceof Future<?>) {
            if (t == null && r instanceof Future<?>) {
                try {
                    Future<?> future = (Future<?>) r;
                    if (future.isDone()) {
                        future.get();
                    }
                } catch (CancellationException ce) {
                    t = ce;
                } catch (ExecutionException ee) {
                    t = ee.getCause();
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
            if (t != null) {
                log.error(t.getMessage(), t);
            }
        }
    }

    /**
     * 停止线程池
     */
    public static void shutdown(ExecutorService pool) {
        if (pool != null && !pool.isShutdown()) {
            pool.shutdown();
            try {
                if (!pool.awaitTermination(ThreadPoolConstant.TIME_OUT, TimeUnit.SECONDS)) {
                    pool.shutdownNow();
                    if (!pool.awaitTermination(ThreadPoolConstant.TIME_OUT, TimeUnit.SECONDS)) {
                    }
                }
            } catch (InterruptedException ie) {
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}